package com.cookor.poi.modules.cms.service;

import com.alibaba.fastjson.JSONArray;
import com.cookor.poi.modules.cms.dao.CmsSurveryQuestionDao;
import com.cookor.poi.modules.cms.entity.*;
import com.cookor.poi.modules.sys.utils.UserUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.cookor.poi.common.utils.IdGen;
import com.cookor.poi.common.utils.StringUtils;
import com.cookor.poi.modules.cms.dao.CmsSurveryDao;
import com.cookor.poi.modules.cms.dao.CmsSurveryOptionDao;
import com.cookor.poi.modules.cms.dao.CmsSurveryResultDao;
import com.cookor.poi.modules.cms.entity.*;
import org.apache.commons.lang3.StringEscapeUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
@Transactional(readOnly = true)
public class SurveryService {

    @Resource
    private CmsSurveryDao cmsSurveryDao;
    @Resource
    private CmsSurveryQuestionDao cmsSurveryQuestionDao;
    @Resource
    private CmsSurveryOptionDao cmsSurveryOptionDao;
    @Resource
    private CmsSurveryResultDao cmsSurveryResultDao;


    @Transactional(readOnly = false)
    public void save(CmsSurvery survery, String surveryObj){
        String surveryId = null;
        if (!UserUtils.getSubject().isPermitted("cms:survery:audit")){
            survery.setDelFlag(Article.DEL_FLAG_AUDIT);
        }
        if(survery != null && StringUtils.isNotBlank(survery.getId())){
            surveryId = survery.getId();
            survery.setUpdateDate(new Date());
            survery.setUpdater(UserUtils.getUser().getName());
            cmsSurveryDao.updateByPrimaryKeySelective(survery);
        }else{
            surveryId = IdGen.uuid();
            survery.setId(surveryId);
            survery.setCreator(UserUtils.getUser().getName());
            survery.setCreateDate(new Date());
            survery.setUpdateDate(survery.getCreateDate());
            cmsSurveryDao.insertSelective(survery);
        }


        /** json转义*/
        String json = StringEscapeUtils.unescapeHtml4(surveryObj);
        /** 获取所有问题*/
        List<CmsSurveryQuestion> questions = JSONArray.parseArray(json, CmsSurveryQuestion.class);
        CmsSurveryQuestion question;
        String questionId;
        List<CmsSurveryOption> options;
        /** 添加所有问题*/
        cmsSurveryQuestionDao.deleteBySurveryId(surveryId);
        for(CmsSurveryQuestion item : questions){
            if(StringUtils.isBlank( item.getId())){
                questionId = IdGen.uuid();
                item.setId(questionId);
            }
            item.setSurveryId(surveryId);
            cmsSurveryQuestionDao.insertSelective(item);
            options = JSONArray.parseArray(item.getOptionStr(), CmsSurveryOption.class);
            /** 添加所有选项*/
            cmsSurveryOptionDao.deleteByQuestionId(item.getId());
            for(CmsSurveryOption option : options){
                option.setId(IdGen.uuid());
                option.setQusetionId(item.getId());
                cmsSurveryOptionDao.insertSelective(option);
            }
        }
    }

    public CmsSurvery get(String id) {
        return cmsSurveryDao.selectByPrimaryKey(id);
    }

    public PageInfo<CmsSurvery> findPage(CmsSurvery survery, String pageNum, String pageSize) {
        // 更新过期的权重，间隔为“6”个小时
//        Date updateExpiredWeightDate =  (Date) CacheUtils.get("updateExpiredWeightDateByArticle");
//        if (updateExpiredWeightDate == null || (updateExpiredWeightDate != null
//                && updateExpiredWeightDate.getTime() < new Date().getTime())){
//            dao.updateExpiredWeight(article);
//            CacheUtils.put("updateExpiredWeightDateByArticle", DateUtils.addHours(new Date(), 6));
//        }
        CmsSurveryExample surveryExample = new CmsSurveryExample();
        CmsSurveryExample.Criteria criteria = surveryExample.createCriteria();
        if(StringUtils.isBlank(pageNum)){
            pageNum = "1";
        }
        if(StringUtils.isBlank(pageSize)){
            pageSize = "15";
        }
        if(survery != null && StringUtils.isNotBlank(survery.getTitle())){
            criteria.andTitleLike("%" + survery.getTitle() + "%");
        }
        criteria.andDelFlagEqualTo(survery.getDelFlag() == null ? "0" : survery.getDelFlag());
        String orderBy = "weight desc, update_date desc"; //（排序字段 空格 排序方式,排序字段 空格 排序方式）
        PageHelper.startPage(Integer.valueOf(pageNum), Integer.valueOf(pageSize), orderBy);
//        Page<CmsQuestion> page = new Page<CmsQuestion>();
//        page.setOrderBy(orderBy);
//        return super.findPage(page, question);
        List<CmsSurvery> cmsSurverys = cmsSurveryDao.selectByExample(surveryExample);
        PageInfo<CmsSurvery> page = new PageInfo<CmsSurvery>(cmsSurverys);
//        page.setList(cmsQuestions);
        return page;
    }

    @Transactional(readOnly = false)
    public void delete(CmsSurvery survery) {
        cmsSurveryDao.updateByPrimaryKeySelective(survery);
    }

    @Transactional(readOnly = false)
    public void updateHitsAddOne(String id) {
        cmsSurveryDao.updateHitsAddOne(id);
    }

    public CmsSurvery stats(CmsSurvery survery)throws Exception {
        survery = cmsSurveryDao.selectByPrimaryKey(survery.getId());
        List<CmsSurveryResult> result = cmsSurveryResultDao.queryCount(survery.getId());
        for(CmsSurveryQuestion question : survery.getQuestionList()){
            for(CmsSurveryOption option : question.getOptions()){
                for(CmsSurveryResult item : result){
                    if(item.getName().equals(option.getName())
                            && option.getQusetionId().equals(item.getQusetionId())){
                        option.setCount(item.getCount());
                    }
                }
            }
        }
        return survery;
    }

    @Transactional(readOnly = false)
    public void addResults(List<CmsSurveryResult> cmsSurveryResults) {
        if (cmsSurveryResults == null || cmsSurveryResults.size()==0){
            return;
        }
        CmsSurveryResult result;
        for(CmsSurveryResult item : cmsSurveryResults){
            result = item;
            cmsSurveryResultDao.insertSelective(result);
        }
    }
}
